import { NextResponse } from 'next/server'
import { Spot } from '@binance/connector'

// 处理 POST 请求
export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { symbols = ['BTCUSDT'], intervals = ['1h'], limit = 10 } = body

    if (!Array.isArray(symbols) || !Array.isArray(intervals)) {
      return NextResponse.json({
        message: 'Invalid parameters: symbols and intervals must be arrays',
        success: false
      }, { status: 400 })
    }

    const client = new Spot() // 无需签名，仅公共数据

    const result: Record<string, any> = {}

    for (const symbol of symbols) {
      result[symbol] = {}
      for (const interval of intervals) {
        const { data } = await client.klines(symbol, interval, { limit })
        result[symbol][interval] = data.map(k => ({
          openTime: new Date(k[0]).toISOString(),
          open: +k[1],
          high: +k[2],
          low: +k[3],
          close: +k[4],
          volume: +k[5],
        }))
      }
    }

    return NextResponse.json({
      success: true,
      data: result
    }, { status: 200 })

  } catch (error) {
    return NextResponse.json({
      message: 'An error occurred',
      error: error instanceof Error ? error.message : String(error),
      success: false
    }, { status: 500 })
  }
}

// 保留默认导出（支持 Next.js App Router）
export default function handler(request: Request) {
  if (request.method === 'POST') {
    return POST(request)
  }

  return NextResponse.json({
    message: 'Method not allowed',
    allowedMethods: ['POST']
  }, { status: 405 })
}
